package org.luxor.commons.redis.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.luxor.commons.redis.annotation.RedisCachePut;
import org.luxor.commons.redis.client.RedisObjectClient;
import org.luxor.commons.redis.component.KeyGenerator;
import org.luxor.commons.redis.component.RedisKeys;
import org.luxor.commons.redis.component.ReflectUtil;

/**
 * Redis缓存加载AOP
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-07-17 23:30
 */
@Aspect
public class CachePutAspect {
    private RedisObjectClient redisObjectClient;

    public void setRedisClientObject(RedisObjectClient redisObjectClient) {
        this.redisObjectClient = redisObjectClient;
    }

    /**
     * 定义缓存逻辑
     */
    @Around("@annotation(org.luxor.commons.redis.annotation.RedisCachePut)")
    public Object cache(ProceedingJoinPoint pjp) throws Throwable {
        //获取所有参数
        RedisCachePut redisCachePut = ReflectUtil.getMethod(pjp).getAnnotation(RedisCachePut.class);
        String fieldKey = KeyGenerator.INSTANCE.getCacheKeyName(pjp, redisCachePut);
        fieldKey = RedisKeys.buildCacheKey(fieldKey);

        Object result = pjp.proceed();
        redisObjectClient.set(fieldKey, result, redisCachePut.expireTime());
        return result;
    }

}